package load

import (
	"sync"
	"time"
	"util"
)

/**
 * @Author：落叶知秋
 * @Date：15:20 2022/6/16
 * @note：
 **/
var timeNow int

// MovePlayer 定义玩家移动的函数
func (this *Loadmap) MovePlayer(dir string) {
	this.player.Row, this.player.Col = makeMove(this.player.Row, this.player.Col, dir)
	//匿名函数
	removeDot := func(row, col int) {
		Maze[row] = Maze[row][0:col] + " " + Maze[row][col+1:]
	}
	switch Maze[this.player.Row][this.player.Col] {
	case '.':
		this.NumDots--
		this.Score++
		removeDot(this.player.Row, this.player.Col) //除掉这个点
	case 'X':
		this.Score += 10
		this.Num_Pill++
		removeDot(this.player.Row, this.player.Col) //去除掉这个点
		updateGhosts(this.ghosts, util.GhostStatusBlue)
		timeNow = time.Now().Second()
		go this.processPill()
	}
}

var pilMx sync.Mutex
var ghostStatusMx sync.RWMutex
var jud = false

func (this *Loadmap) processPill() {
	//上锁

	pilMx.Lock()
	jud = true
	jud = false
	for {
		if time.Now().Second()-timeNow == 10 || jud {
			updateGhosts(this.ghosts, util.GhostStatusNormal)
			break
		}
	}
	pilMx.Unlock()
}
func updateGhosts(ghosts []*util.Ghost, s util.GhostStatus) {
	ghostStatusMx.Lock()
	defer ghostStatusMx.Unlock()
	for _, g := range ghosts {
		g.Status = s
	}
}

func (this *Loadmap) MoveGhost() {

	for _, ghost := range this.ghosts {
		dir := drawDirection()
		ghost.Position.Row, ghost.Position.Col = makeMove(ghost.Position.Row, ghost.Position.Col, dir)
	}
}

//分别传入三个参数，坐标还有动的方向
func makeMove(oldRow, oldCol int, dir string) (newRow, newCol int) {
	newRow, newCol = oldRow, oldCol
	n1, n2 := len(Maze), len(Maze[0])
	//进行判断
	switch dir {
	//上
	case "UP":
		newRow = newRow - 1
		if newRow < 0 {
			newRow = n1 - 1
		}
	//下
	case "DOWN":
		newRow = newRow + 1
		if newRow >= n1 {
			newRow = 0
		}
	//左
	case "RIGHT":
		newCol = newCol + 1
		if newCol >= n2 {
			newCol = 0
		}
		//右
	case "LEFT":
		newCol = newCol - 1
		if newCol < 0 {
			newCol = n2 - 1
		}
	}
	//进行判断是不是墙
	if Maze[newRow][newCol] == '#' {
		newRow, newCol = oldRow, oldCol
	}
	return
}
